﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPropertyAnimation>
#include <QScreen>
#include <QToolButton>
#include <QTimer>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 测试QPropertyAnimation
    ui->myWidget->installEventFilter(this);
    QPropertyAnimation *animation = new QPropertyAnimation(ui->myWidget, "geometry");
    animation->setDuration(200);
    animation->setStartValue(QRect(0,0,160,70));
    animation->setEndValue(QRect(-150, 0, 160, 70));
    animation->start();
    //ui->myWidget->move(0,0); // 移动到窗口的左上角

    // 测试吸附效果窗口
    ui->btn_function->installEventFilter(this); // 给控件安装事件
    dockWindow = new DockWindow(this);
    dockWindow->SetSize(QSize(dockWindow->width(),dockWindow->height()));
    dockWindow->SetStickArea(StickArea::kLRSide,QPoint(this->width()-dockWindow->width(),20));
    auto pat = dockWindow->palette();
    pat.setColor(QPalette::Window, Qt::white);
    dockWindow->setPalette(pat);

    qDebug() << this->width() << dockWindow->width();
    ui->myWidget->move(QPoint(this->size().width()-dockWindow->width(),20)); // 移动到窗口的指定位置

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *e)
{
    if(dockWindow!=nullptr)
        dockWindow->Update();
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if ( obj->inherits("QToolButton"))//指定某个控件
    {
        if(static_cast<QToolButton*>(obj)==ui->btn_function)
        {
            switch (event->type())
            {
            case QEvent::Enter:
            {
                QTimer::singleShot(300,
                                   [this]{
                    if(dockWindow!=nullptr&&dockWindow->isHidden())
                    {
                        dockWindow->SetExpand();
                    }
                }
                );
                break;
            }
            case QEvent::Leave:
                break;
            default:
                break;
            }
        }
    }
    if(static_cast<QWidget*>(obj) == ui->myWidget && (event->type() == QEvent::Enter || event->type() == QEvent::Leave))
    {
        QPropertyAnimation *animation = new QPropertyAnimation(ui->myWidget, "geometry");
        animation->setDuration(200);
        switch (event->type()) {
        case QEvent::Enter:
        {
            if(ui->myWidget->x() < 0)
            {
                animation->setStartValue(QRect(-150,0,160,70));
                animation->setEndValue(QRect(0, 0, 160, 70));
            }

        }break;
        case QEvent::Leave:
        {
            if(ui->myWidget->x()>=0)
            {
                animation->setStartValue(QRect(0,0,160,70));
                animation->setEndValue(QRect(-150, 0, 160, 70));
            }
        }break;
        default:
            break;
        }
        animation->start();
    }
    return QWidget::eventFilter(obj, event);
}
